"""Sensors for Voice Assistant Control."""
from __future__ import annotations

from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import DOMAIN
from homeassistant.util import slugify

async def async_setup_entry(
    hass: HomeAssistant,
    entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up the Voice Assistant Control sensors."""
    data = hass.data[DOMAIN][entry.entry_id]
    websocket = data["websocket"]
    tunnel_client = data["tunnel_client"]
    
    # 创建连接状态传感器
    connection_sensor = VoiceAssistantConnectionSensor(entry,'语音助手')
    websocket._connection_state_callback = connection_sensor.update_state
    
    # 创建隧道状态传感器
    tunnel_client_sensor = VoiceAssistantConnectionSensor(entry,'远程访问')
    tunnel_client._connection_state_callback = tunnel_client_sensor.update_state
    
    async_add_entities([connection_sensor, tunnel_client_sensor], True)

class VoiceAssistantConnectionSensor(SensorEntity):
    """传感器显示语音助手的连接状态."""

    def __init__(self, entry: ConfigEntry,attr_name) -> None:
        """初始化传感器."""
        self._attr_name = f"{attr_name}连接状态"
        self._attr_unique_id = f"{entry.entry_id}_connection_{slugify(attr_name,separator="_")}"
        self._attr_native_value = "已断开"
        self._attr_extra_state_attributes = {
            "connecting": False
        }

    def update_state(self, connected: bool, connecting: bool) -> None:
        """更新传感器状态."""
        self._attr_native_value = "已连接" if connected else "已断开"
        self._attr_extra_state_attributes["connecting"] = connecting
        self.schedule_update_ha_state()

class VoiceAssistantAuthSensor(SensorEntity):
    """传感器显示语音助手的认证状态."""

    def __init__(self, entry: ConfigEntry) -> None:
        """初始化传感器."""
        self._attr_name = "语音助手认证状态"
        self._attr_unique_id = f"{entry.entry_id}_auth"
        self._attr_native_value = "未认证"

    def update_state(self, authenticated: bool) -> None:
        """更新传感器状态."""
        self._attr_native_value = "已认证" if authenticated else "未认证"
        self.schedule_update_ha_state() 